<template>
  <div class="monitor">
    <transition name="el-fade-in-linear">
      <el-dialog :visible.sync="show" width="90%" top="3vh" :show-close="false" @close="onClose"
                 custom-class="m-dialog">
        <div class="-inner" v-if="this.gyro.lines">
          <div class="monitor-chart">
            <div class="monitor-chart_tabs" v-if="this.gyro.cjms=='03'">
              <a @click="player.active='acc'" :class="{'active': this.player.active=='acc'}">加速度</a>
              <a @click="player.active='gyr'" :class="{'active': this.player.active=='gyr'}">陀螺仪</a>
            </div>
            <div class="monitor-chart_page" v-if="this.player.active=='acc'">
              <acc-chart :gyro="gyro" :shows="player.shows"></acc-chart>
            </div>
            <div class="monitor-chart_page" v-if="this.player.active=='gyr'">
              <gyr-chart :gyro="gyro" :shows="player.shows"></gyr-chart>
            </div>
          </div>
          <div class="monitor-options">
            <div class="-forms">
              <div class="row">
                <div class="-forms-col">
                  <span class="label">开始时间</span>
                  <span class="value">
                    <input type="text" v-model="gyro.startTime" readonly="true"/>
                  </span>
                </div>
                <div class="-forms-col">
                  <span class="label">结束时间</span>
                  <span class="value"><input type="text" v-model="gyro.endTime" readonly="true"/></span>
                </div>
              </div>
              <div class="row">
                <div class="-forms-col">
                  <span class="label">采集模式</span>
                  <span class="value"><input type="text" v-model="gyro.showCjms" readonly="true"/></span>
                </div>
                <div class="-forms-col">
                  <span class="label">采集频率</span>
                  <span class="value"><input type="text" v-model="gyro.showCjpl" readonly="true"/></span>
                </div>
              </div>
              <div class="row">
                <div class="-forms-col">
                  <span class="label">采集ODR</span>
                  <span class="value"><input type="text" v-model="gyro.showOdr" readonly="true"/></span>
                </div>
                <div class="-forms-col">
                  <span class="label">采集时长</span>
                  <span class="value"><input type="text" :value="(gyro.times || '0')  + '秒'" readonly="true"/></span>
                </div>
              </div>
              <div class="row">
                <div class="-forms-col">
                  <span class="label">采集字节</span>
                  <span class="value"><input type="text" :value="gyro.total | size" readonly="true"/></span>
                </div>
                <div class="-forms-col">
                  <span class="label">采集帧数</span>
                  <span class="value"><input type="text" :value="(gyro.frames || '0') + '帧'" readonly="true"/></span>
                </div>
              </div>
              <div class="row">
                <div class="-forms-col">
                  <span class="label">开始帧数</span>
                  <span class="value"><input type="text" v-model="controls.startFrame"/></span>
                </div>
                <div class="-forms-col">
                  <span class="label">结束帧数</span>
                  <span class="value"><input type="text" v-model="controls.endFrame"/></span>
                </div>
              </div>
              <div class="-forms-ops">
                <a @click.stop="doQuery">
                  <i class="iconfont icon-yibiaopan"></i>
                  <span>查询</span>
                </a>
              </div>
            </div>
            <div class="-ops">
              <div class="row">
                <div class="-col">
                  <span class="label">进度({{controls.progress}}%) </span>
                  <span class="value"><el-slider v-model="controls.progress" @change="onProgress"></el-slider></span>
                </div>
              </div>
              <div class="row">
                <div class="-col">
                  <span class="label">每页({{controls.step}}帧)</span>
                  <span class="value"><el-slider v-model="controls.step" :min="100" :step="100" :max="1000"
                                                 show-stops></el-slider></span>
                </div>
              </div>
              <div class="row">
                <div class="-col">
                  <span class="label">步长({{controls.skip ||1}}帧)</span>
                  <span class="value"><el-slider v-model="controls.skip" :min="0" :step="100" :max="1000"
                                                 show-stops></el-slider></span>
                </div>
              </div>
              <div class="-ops-as">
                <a @click.stop="doStart" :disabled="controls.auto"><i class="iconfont icon-start"></i>播放</a>
                <a @click.stop="doStop" :disabled="!controls.auto"><i class="iconfont icon-stop"></i>暂停</a>
                <a @click.stop="doClose" class="-close"><i class="iconfont icon-yibiaopan"></i>关闭</a>
              </div>
            </div>
          </div>
        </div>
        <div class="-inner" v-else>
          <swak-loading/>
        </div>
      </el-dialog>
    </transition>
  </div>
</template>

<script>
  import DatasApi from '@/api/datas';
  import 'echarts/lib/chart/line'
  import 'echarts/lib/component/legend'
  import 'echarts/lib/component/toolbox'
  import 'echarts/lib/component/title'
  import Queue from "@/ui/common/lang/queue";
  import Task from '@/ui/common/mixins/queue';
  import Size from '@/ui/common/mixins/size';
  import AccChart from "./charts/acc";
  import GyrChart from "./charts/gyr";
  import SwakLoading from "../../ui/components/loading/loading";

  export default {
	name: "data-monitor",
	components: {SwakLoading, GyrChart, AccChart},
	mixins: [Task, Size],
	data() {
	  return {
		show: false,
		gyro: {},
		player: {
		  loading: false,
		  timer: null,
		  queue: Queue.newQueue(),
		  shows: {
			data: [],
			legend: [],
			series: [],
		  },
		  active: 'acc'
		},
		controls: {
		  step: 100, // 每页显示的帧数， 每次查询的数据
		  speed: 100, // 目前没啥用
		  skip: 0, // 步长
		  auto: true, // 是否自动加载
		  progress: 0, // 进度条
		  startFrame: '', // 查询开始帧
		  endFrame: '', // 查询结束帧
		  autoLoad: true,// 自动加载，自动加载不显示所有的帧
		},
		initOptions: {
		  renderer: 'svg'
		}
	  }
	},
	props: {
	  visible: {
		type: Boolean,
		default: false
	  },
	  id: {
		type: String,
		default: ''
	  }
	},
	watch: {
	  visible: function () {
		this.show = this.visible;
		if (this.show) {
		  this.doFullQuery();
		}
	  },
	  id: function () {
		if (this.id) {
		  this.reset();
		}
	  },
	  'gyro.cjms': function () {
		if (this.gyro.cjms == '01') {
		  this.player.shows.legend.push('加速度X');
		  this.player.shows.legend.push('加速度Y');
		  this.player.shows.legend.push('加速度Z');
		  this.player.shows.series.push({data: [], name: '加速度X', type: 'line'});
		  this.player.shows.series.push({data: [], name: '加速度Y', type: 'line'});
		  this.player.shows.series.push({data: [], name: '加速度Z', type: 'line'});
		} else if (this.gyro.cjms == '02') {
		  this.player.shows.legend.push('陀螺仪X');
		  this.player.shows.legend.push('陀螺仪Y');
		  this.player.shows.legend.push('陀螺仪Z');
		  this.player.shows.series.push({data: [], name: '陀螺仪X', type: 'line'});
		  this.player.shows.series.push({data: [], name: '陀螺仪Y', type: 'line'});
		  this.player.shows.series.push({data: [], name: '陀螺仪Z', type: 'line'});
		  this.player.active = 'gyr';
		} else if (this.gyro.cjms == '03') {
		  this.player.shows.legend.push('加速度X');
		  this.player.shows.legend.push('加速度Y');
		  this.player.shows.legend.push('加速度Z');
		  this.player.shows.legend.push('陀螺仪X');
		  this.player.shows.legend.push('陀螺仪Y');
		  this.player.shows.legend.push('陀螺仪Z');
		  this.player.shows.series.push({data: [], name: '加速度X', type: 'line'});
		  this.player.shows.series.push({data: [], name: '加速度Y', type: 'line'});
		  this.player.shows.series.push({data: [], name: '加速度Z', type: 'line'});
		  this.player.shows.series.push({data: [], name: '陀螺仪X', type: 'line'});
		  this.player.shows.series.push({data: [], name: '陀螺仪Y', type: 'line'});
		  this.player.shows.series.push({data: [], name: '陀螺仪Z', type: 'line'});
		} else {
		  this.player.shows.legend = [];
		  this.player.shows.series = [];
		  this.player.shows.data = [];
		}
	  },
	  'player.shows.data': function (nv) {
		if (nv && nv.length > 0) {
		  var n = nv[nv.length - 1];
		  this.controls.progress = Math.floor(n / this.gyro.frames * 100);
		}
	  }
	},
	computed: {
	  speed: function () {
		var speed = parseInt(1000 / this.controls.speed);
		return speed;
	  }
	},
	methods: {
	  reset: function () {
		this.controls.step = 100;
		this.controls.speed = 100;
		this.controls.skip = 0;
		this.controls.auto = true;
		this.controls.progress = 0;
		this.controls.startFrame = '';
		this.controls.endFrame = '';
		this.controls.autoLoad = true;
		this.player.queue.clear();
		this.gyro = {};
	  },
	  chart_load: function () {
		// 显示数据
		this.chart_show();

		// 加载数据
		this.auto_data_task_add();

		// 执行下一次
		this.chart_task();
	  },
	  chart_task: function () {
		if (this.player.timer != null) {
		  clearTimeout(this.player.timer);
		}
		this.player.timer = setTimeout(() => {
		  this.chart_load();
		}, this.speed);
	  },
	  chart_show: function () {
		try {
		  // 初始化完成再处理
		  if (this.player.shows.legend.length == 0) {
			return;
		  }

		  //循环添加数据
		  while (true) {
			// 超过一屏显示的数量
			if (this.controls.autoLoad && this.player.shows.data.length > this.controls.step) {
			  this.player.shows.data.splice(0, 1);
			  this.player.shows.series.forEach(serie => {
				serie.data.splice(0, 1);
			  })
			  continue;
			}

			// 添加数据
			var data = this.player.queue.pop();
			if (data) {
			  this.player.shows.data.push(data.no);
			  for (var i = 0; i < data.nums.length; i++) {
				this.player.shows.series[i].data.push(data.nums[i]);
			  }
			  // 没有超过一屏显示的数量
			  if (!this.controls.autoLoad || this.player.shows.data.length < this.controls.step) {
				continue;
			  }
			}

			// 添加之后判断一次
			if (this.controls.autoLoad && this.player.shows.data.length > this.controls.step) {
			  this.player.shows.data.splice(0, 1)
			  this.player.shows.series.forEach(serie => {
				serie.data.splice(0, 1);
			  })
			}

			// 不需要处理
			break;
		  }
		} catch (e) {
		}
	  },
	  auto_data_task_add: function () {
		if ((!this.gyro.frames || this.gyro.endFrame < this.gyro.frames) && (this.player.queue.size() / this.controls.step) < 1
		  && this.controls.autoLoad) {
		  if (!this.player.loading) {
			this.player.loading = true;
			var startFrame = this.gyro.endFrame;
			var endFrame = 0;
			var skip = this.controls.skip || 1;
			var step = 10;//this.controls.step;
			this._data_task_add({
			  id: this.id,
			  startFrame: startFrame,
			  endFrame: endFrame,
			  skip: skip,
			  step: step,
			});
			this._data_task_end();
		  }
		}
	  },
	  manual_data_task_add: function () {
		if (!this.player.loading) {
		  this.player.loading = true;
		  var startFrame = this.controls.startFrame;
		  var endFrame = this.controls.endFrame;
		  var skip = this.controls.skip || 1;
		  var step = 1000;
		  var page = (endFrame - startFrame + 1) / skip / step;
		  for (var i = 0; i <= page; i++) {
			this._data_task_add({
			  id: this.id,
			  startFrame: startFrame + i * skip * step,
			  endFrame: endFrame,
			  skip: skip,
			  step: step,
			});
		  }
		  this._data_task_end();
		}
	  },
	  _data_task_add: function (query) {
		this.__task_add(() => {
		  return new Promise((resolve, reject) => {
			if (this.id) {
			  DatasApi.chart(query).then(res => {
				this.data_task_result(res.obj);
				resolve();
			  }, () => {
				resolve();
			  }).catch(() => {
				resolve();
			  });
			} else {
			  resolve();
			}
		  });
		});
	  },
	  _data_task_end: function () {
		this.__task_add(() => {
		  return new Promise((resolve, reject) => {
			this.player.loading = false;
			resolve();
		  });
		})
	  },
	  data_task_result: function (data) {
		this.gyro = data;
		var lines = this.gyro.lines;
		for (var i = 0; i < lines.length; i++) {
		  var line = lines[i];
		  this.player.queue.push({
			no: line.sn,
			nums: line.data.split(',')
		  });
		}
	  },
	  onClose: function () {
		this.$emit('update:visible', false);
		this.doStop();
	  },
	  onProgress: function () {
		this.doStop();
		this.doClear();
		this.controls.startFrame = parseInt(this.gyro.frames * this.controls.progress / 100);
		this.gyro.endFrame = 0;
		this.doStart();
	  },
	  doClose: function () {
		this.show = false;
		this.$emit('update:visible', false);
		this.onClose();
	  },
	  doStart: function () {
		this.controls.auto = true;
		this.controls.autoLoad = true;
		this.chart_task();
	  },
	  doStop: function () {
		this.controls.auto = false;
		this.controls.autoLoad = true;
		if (this.player.timer != null) {
		  clearTimeout(this.player.timer);
		}
	  },
	  doClear: function () {
		this.player.shows.data = [];
		this.player.shows.series.forEach(serie => {
		  serie.data = []
		});
		this.player.queue.clear();
	  },
	  doQuery: function () {
		this.doStop();
		this.controls.autoLoad = false;
		this.controls.startFrame = parseInt(this.controls.startFrame) || 1;
		this.controls.endFrame = parseInt(this.controls.endFrame) || 500;
		if (!(this.controls.endFrame > this.controls.startFrame)) {
		  this.$message.error('请正确填写查询的起始帧！');
		  return;
		}
		this.doClear();
		this.manual_data_task_add();
		this.chart_task();
	  },
	  doFullQuery: function () {
		DatasApi.get(this.id).then((data) => {
		  this.gyro = data.obj;
		  this.controls.startFrame = 1;
		  this.controls.endFrame = this.gyro.frames;
		  this.controls.skip = parseInt(this.gyro.showOdr);
		  this.doQuery();
		});
	  }
	},
	destroyed() {
	  if (this.player.timer != null) {
		clearTimeout(this.player.timer);
	  }
	}
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  @require "../../ui/common/stylus/variable.styl"
  .monitor {
    .-inner {
      height 92vh;
      display flex;
      flex-direction: column;

      .monitor-chart {
        .monitor-chart_tabs {
          background-color $color-bg;
          margin -10px;

          a {
            padding 10px;
            display inline-block;
            font-size 22px;
            cursor pointer;
            padding-left 20px;
            padding-right 20px;

            &.active {
              background-color $color-white;
              color $color-warning
              font-weight bold;
            }
          }
        }
      }

      .monitor-options {
        flex 1;
        display flex;

        .-forms {
          flex 1;
          background-color $color-bg;
          padding 10px;
          margin-right 10px;

          .-forms-col {
            display flex;
            line-height 30px;
            margin-bottom 5px;
            margin-right 5px;

            .label {
              width 80px;
            }

            .value {
              flex 1;

              input {
                height 30px;
                line-height 30px;
                display block;
                border 1px solid #ddd;
                padding 0 0 0 3px;
                box-sizing border-box;
              }
            }
          }

          .-forms-ops {
            text-align right;
            padding-right 8px;

            a {
              display inline-block;
              border 1px solid $color-warning;
              background-color $color-warning;
              border-radius 3px;
              cursor pointer;
              transition: all 0.1s ease-out;
              flex 1;
              height 40px;
              line-height 40px;
              text-align center;
              font-size 16px;
              margin 0 5px;
              padding 0 10px;
              color $color-white;

              i {
                margin-right 10px;
              }

              &:hover {
                position relative;
                transform: scale(1.1);
                box-shadow 1px 2px 5px $color-warning;
              }
            }
          }
        }

        .-ops {
          flex 1;
          background-color $color-bg;
          padding 10px 10px 5px 10px;
          box-sizing border-box;

          .-col {
            flex 1;
            display flex;

            .label {
              width 110px;
              line-height 38px;
            }

            .value {
              flex 1;
            }
          }

          .-ops-as {
            display flex;
            margin-left -5px;
            margin-right -5px;
            margin-top 25px;

            a {
              display inline-block;
              border 1px solid $color-border;
              background-color $color-white;
              border-radius 3px;
              cursor pointer;
              transition: all 0.1s ease-out;
              flex 1;
              height 40px;
              line-height 40px;
              text-align center;
              font-size 16px;
              margin 0 5px;
              color $color-success;

              i {
                margin-right 10px;
              }

              &:hover {
                position relative;
                transform: scale(1.1);
                color $color-success;
                box-shadow 1px 2px 5px $color-border;
              }

              &[disabled] {
                color $color-light-grey;
              }

              &[disabled]:hover {
                position relative;
                transform: scale(1);
                color $color-light-grey;
                box-shadow 0px 0px 0px $color-border;
              }
            }

            .-close {
              display inline-block;
              border 1px solid $color-warning;
              background-color $color-warning;
              border-radius 3px;
              cursor pointer;
              transition: all 0.1s ease-out;
              flex 1;
              height 40px;
              line-height 40px;
              text-align center;
              font-size 16px;
              margin 0 5px;
              padding 0 10px;
              color $color-white;

              i {
                margin-right 10px;
              }

              &:hover {
                position relative;
                transform: scale(1.1);
                box-shadow 1px 2px 5px $color-warning;
                color $color-white;
              }
            }
          }
        }

        .row {
          display flex;
        }
      }
    }
  }
</style>